package com.lsh.utils;


import com.google.gson.Gson;
import com.lsh.constants.MessageConstant;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class QiNiuUtils {

    private static final String ACCESSKEY = "B2c6vfnFtQbYBFVm0slfpD_gqsc6rCfU53e1gkrA";
    private static final String SECRETKEY = "tShf7fNvQZpBxeSSF30PrtHkXdNet8li7ncgc1R2";
    private static final String BUCKET = "devinen";
    public static final String DOMAIN= "http://rfdez533a.hb-bkt.clouddn.com/";

    public static void main(String[] args) {
//        uploadFile("C:\\Users\\devin\\Desktop\\按键图片\\绝地求生.png","dd2.jpg");
        //removeFiles("20190529083159.jpg","20190529083241.jpg");
        System.out.println(getAllImgName());
    }

    /**
     * 批量删除
     * @param filenames 需要删除的文件名列表
     * @return 删除成功的文件名列表
     */
//    public static List<String> removeFiles(String... filenames){
//        // 删除成功的文件名列表
//        List<String> removeSuccessList = new ArrayList<String>();
//        if(filenames.length > 0){
//            // 创建仓库管理器
//            BucketManager bucketManager = getBucketManager();
//            // 创建批处理器
//            BucketManager.Batch batch = new BucketManager.Batch();
//            // 批量删除多个文件
//            batch.delete(BUCKET,filenames);
//            try {
//                // 获取服务器的响应
//                Response res = bucketManager.batch(batch);
//                // 获得批处理的状态
//                BatchStatus[] batchStatuses = res.jsonToObject(BatchStatus[].class);
//                for (int i = 0; i < filenames.length; i++) {
//                    BatchStatus status = batchStatuses[i];
//                    String key = filenames[i];
//                    System.out.print(key + "\t");
//                    if (status.code == 200) {
//                        removeSuccessList.add(key);
//                        System.out.println("delete success");
//                    } else {
//                        System.out.println("delete failure");
//                    }
//                }
//            } catch (QiniuException e) {
//                e.printStackTrace();
//                throw new RuntimeException(MessageConstant.PIC_UPLOAD_FAIL);
//            }
//        }
//        return removeSuccessList;
//    }
    /**
     * 批量删除更新版
     * @param filenames 需要删除的文件名列表
     * @return 删除成功的文件名列表
     */
    public static List<String> removeFiles(String... filenames){
        if (filenames.length == 0){
            return null;
        }
        List<String> removeSuccessList = new ArrayList<String>();
        try {
        BucketManager bucketManager = getBucketManager();
        BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
        batchOperations.addDeleteOp(BUCKET, filenames);
        Response response = bucketManager.batch(batchOperations);
        BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
        for (int i = 0; i < filenames.length; i++) {
            BatchStatus status = batchStatusList[i];
            String key = filenames[i];
            System.out.print(key + "\t");
            if (status.code == 200) {
                removeSuccessList.add(key);
                System.out.println("delete success");
            } else {
                System.out.println(status.data.error);
            }
        }
    } catch (QiniuException ex) {
        System.err.println(ex.response.toString());
    }
        return removeSuccessList;
    }
    public static void uploadFile(String localFilePath, String savedFilename){
        UploadManager uploadManager = getUploadManager();
        String upToken = getToken();
        try {
            Response response = uploadManager.put(localFilePath, savedFilename, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(String.format("key=%s, hash=%s",putRet.key, putRet.hash));
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            throw new RuntimeException(MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    public static void uploadViaByte(byte[] bytes, String savedFilename){
        UploadManager uploadManager = getUploadManager();
        String upToken = getToken();
        try {
            Response response = uploadManager.put(bytes, savedFilename, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
            throw new RuntimeException(MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 获取空间所有图片名字
     * @return
     */
    public static List<String> getAllImgName(){
        List<String> name = new LinkedList<>();

        BucketManager bucketManager = getBucketManager();
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(BUCKET, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                name.add(item.key);
            }
        }
        return name;
    }
    private static String getToken(){
        // 创建授权
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        // 获得认证后的令牌
        String upToken = auth.uploadToken(BUCKET);
        return upToken;
    }
//Region.region1()
    private static UploadManager getUploadManager(){
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Region.region1());
        //构建上传管理器
        return new UploadManager(cfg);
    }

    private static BucketManager getBucketManager(){
        // 创建授权信息
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        // 创建操作某个仓库的管理器
        return new BucketManager(auth, new Configuration(Region.region1()));
    }

}
